from datetime import datetime
from django import forms
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.contrib.sites.models import Site
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template.defaultfilters import slugify
from django.utils.translation import gettext as _
from django.views.generic import date_based, list_detail

from models import Channel, Podcast
from os.path import splitext

def archive_index(request, channel):
    qs = Podcast.published_objects.filter(channel__site = settings.SITE_ID, 
	                                  channel__slug = channel)
    channel = Channel.objects.get(site = settings.SITE_ID,
                                slug = channel)
    site = Site.objects.get(id=settings.SITE_ID)
    return date_based.archive_index(request, queryset = qs, 
	                            date_field = 'pub_date',
				    extra_context={'channel': channel, 'site': site,})

def archive_year(request, channel, year):
    qs = Podcast.published_objects.filter(channel__site = settings.SITE_ID, 
	                                  channel__slug = channel)
    channel = Channel.objects.get(site = settings.SITE_ID,
                                slug = channel)
    site = Site.objects.get(id=settings.SITE_ID)
    return date_based.archive_year(request, queryset = qs, year = year,
	                           date_field = 'pub_date', make_object_list = True,
				   extra_context={'channel': channel, 'site': site,})

def archive_month(request, channel, year, month):
    qs = Podcast.published_objects.filter(channel__site = settings.SITE_ID, 
	                                  channel__slug = channel)
    channel = Channel.objects.get(site = settings.SITE_ID,
                                slug = channel)
    site = Site.objects.get(id=settings.SITE_ID)
    return date_based.archive_month(request, queryset = qs, year = year,
	                            month = month, date_field = 'pub_date',
				    extra_context={'channel': channel, 'site': site,})

def archive_day(request, channel, year, month, day):
    qs = Podcast.published_objects.filter(channel__site = settings.SITE_ID, 
	                                  channel__slug = channel)
    channel = Channel.objects.get(site = settings.SITE_ID,
                                slug = channel)
    site = Site.objects.get(id=settings.SITE_ID)
    return date_based.archive_day(request, queryset = qs, year = year,
	                          month = month, day = day,
				  date_field = 'pub_date',
				  extra_context={'channel': channel, 'site': site,})
    
def archive_today(request, channel):
    qs = Podcast.published_objects.filter(channel__site = settings.SITE_ID, 
	                                  channel__slug = channel)
    channel = Channel.objects.get(site = settings.SITE_ID,
                                slug = channel)
    site = Site.objects.get(id=settings.SITE_ID)
    return date_based.archive_today(request, queryset = qs, 
	                            date_field = 'pub_date',
				    extra_context={'channel': channel, 'site': site,})

def object_detail(request, channel, slug, year, month, day):
    qs = Podcast.published_objects.filter(channel__site = settings.SITE_ID, 
	                                  channel__slug = channel)
    channel = Channel.objects.get(site = settings.SITE_ID,
                                slug = channel)
    site = Site.objects.get(id=settings.SITE_ID)
    return list_detail.object_detail(request, queryset = qs, slug = slug,
				     extra_context={'channel': channel, 'site': site,})

class AudioField(forms.FileField):
    def __init__(self, *args, **kwargs):
        super(AudioField, self).__init__(*args, **kwargs)
        self.label = _(u'Audio file')
        self.helptext = _(u'Select an mp3 or ogg audio file')

    def clean(self, data):
        f = super(AudioField, self).clean(data)
        file_types = ('application/ogg', 'audio/mp3')
        file_exts = ('.mp3', '.ogg')
        # TODO: Also check the first X bytes of the files to see if
        # their content-types match.
        if not splitext(f.filename)[1].lower() in file_exts \
               and not data['content-type'] in file_types:
            raise forms.ValidationError(_(u'Audio types accepted: %s' % ' '.join(file_exts)))
        return f

@login_required
def add_edit_channel(request, id=None):
    if id is None:
        AudioForm = forms.models.form_for_model(Channel)
        AudioForm.base_fields['slug'].widget = forms.widgets.HiddenInput()
        AudioForm.base_fields['slug'].required = False
    else:
        AudioForm = forms.models.form_for_instance(Podcast.objects.get(id=id))

    # These widgets are shown in the Admin view, but not needed by
    # regular users.
    AudioForm.base_fields['site'].widget = forms.widgets.HiddenInput()
    AudioForm.base_fields['site'].required = False
    AudioForm.base_fields['description'].widget = forms.widgets.HiddenInput()
    AudioForm.base_fields['description'].required = False

    if request.method == 'POST':
        form = AudioForm(request.POST)
        if form.is_valid():
            channel = form.save(commit=False)
            # The current site we're using
            channel.site = Site.objects.get(id=settings.SITE_ID)
            channel.slug = slugify(channel.name)
            channel.save()
            return HttpResponseRedirect(channel.get_absolute_url())
    else:
        form = AudioForm()

    return render_to_response('podcasts/channel_add.html', {'form': form})


@login_required
def add_edit_podcast(request, id=None):
    if id is None: # Add
        AudioForm = forms.models.form_for_model(Podcast)
        AudioForm.base_fields['slug'].widget = forms.widgets.HiddenInput()
        AudioForm.base_fields['slug'].required = False
    else: # Edit
        AudioForm = forms.models.form_for_instance(Podcast.objects.get(id=id))

    # These widgets are shown in the Admin view, but not needed by
    # regular users.
    AudioForm.base_fields['user'].widget = forms.widgets.HiddenInput()
    AudioForm.base_fields['user'].required = False
    AudioForm.base_fields['content_type'].widget = forms.widgets.HiddenInput()
    AudioForm.base_fields['content_type'].required = False
    AudioForm.base_fields['pub_date'].widget = forms.widgets.HiddenInput()
    AudioForm.base_fields['pub_date'].required = False
    AudioForm.base_fields['audio'] = AudioField()

    if request.method == 'POST':
        post_data = request.POST.copy()
        post_data.update(request.FILES)
        form = AudioForm(request.POST, request.FILES)
        if form.is_valid():
            audio = form.save(commit=False)
            audio.user = request.user
            audio.pub_date = datetime.now()
            audio.slug = slugify(audio.title)
            audio.save()
            return HttpResponseRedirect(audio.get_absolute_url())
    else:
        form = AudioForm()

    return render_to_response('podcasts/podcast_add.html', {'form': form})
